<template>
  <div class="setting">
    <div class="tips">
      操作说明
      <a-tooltip placement="rightBottom">
        <template #title>说明：开启分级保护时会同步开启密级和账号安全设置，并将网站设置为需登录才能浏览。开启后可在相应的模块中对初始设置值进行调整。
          给用户赋予安全员角色时请先为其添加用户密级设置及用户日志菜单权限，赋予审计员角色时请先为其添加用户日志菜单权限。</template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>
    <a-form :model="formState" autoComplete="off" labelAlign="right" ref="threeMemberForm">
      <a-form-item :name="['enable']" :label="formState.status_setting.label">
        <a-switch v-model:checked="formState['enable']"></a-switch>
        <span class="isOpen">{{ formState["enable"] ? "是" : "否" }}</span>
      </a-form-item>
      <a-form-item v-if="formState.enable" :name="['ClassificationMark', 'value']" :label="formState.ClassificationMark.label" :rules="[formState.ClassificationMark.rule]">
        <div style="display: flex;align-items: center">
          <a-input  style="width: 300px;height: 32px;"  v-model:value="formState.ClassificationMark.value" allowClear maxLength="10" ></a-input>
        <div style="margin-left:8px">
      <a-tooltip placement="rightBottom">
        <template #title>输入系统标记后，在系统登录页以及系统顶部会显示密级标记。</template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
        </div>
    </div>
      </a-form-item>
      <a-form-item :name="['userSecretId']" :label="formState.secret_setting.label"
        :rules="[formState.secret_setting.rule]" v-if="formState.enable && 0">
        <a-select placeholder="请选择" class="userSecret" v-model:value="formState['userSecretId']"
          :options="userSecretIdOptions" allow-clear></a-select>
        <span class="ant-form-item-explain-error" style="font-size: 12px; margin-left: 12px;"
          v-if="isDeleteSid && !formState['userSecretId']">所选密级已被删除，请重新选择！</span>
        <!-- <a-tooltip placement="rightBottom">
          <template #title
            >设为系统标记后，在系统登录页以及系统顶部LOGO旁会显示密级标记。</template
          >

          <span style="margin-left: 24px" class="iconfont icon-hint1"></span>
        </a-tooltip> -->
      </a-form-item>
      <a-form-item :name="['enableContentCtl']" :label="formState.ctl_setting.label" :rules="[formState.ctl_setting.rule]"
        v-if="formState.enable">
        <a-radio-group v-model:value="formState['enableContentCtl']" @change="enableContentCtl">
          <a-radio :value="true">是</a-radio>
          <a-radio :value="false">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item :name="['enableContentAnnexCtl']" :label="formState.Annex_setting.label"
        :rules="[formState.Annex_setting.rule]" v-if="formState.enable && formState['enableContentCtl']">
        <a-radio-group v-model:value="formState['enableContentAnnexCtl']">
          <a-radio :value="true">是</a-radio>
          <a-radio :value="false">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="" v-if="formState.enable">
        <div class="titleSetting">
          {{ formState.section }}
        </div>
      </a-form-item>
      <a-form-item :name="['securityManagers']" :label="formState.safeManager_setting.label"
        :rules="[formState.safeManager_setting.rule]" v-if="formState.enable">
        <a-input-group compact @click="selectMember('securityManagers')" class="a-input-group_manage">
          <a-input v-model:value="securityManagers" placeholder="请选择" class="selectInput" />
          <a-button type="primary">选择</a-button>
        </a-input-group>
      </a-form-item>
      <a-form-item :name="['auditManagers']" :label="formState.auditManager_setting.label"
        :rules="[formState.auditManager_setting.rule]" v-if="formState.enable">
        <a-input-group compact @click="selectMember('auditManagers')" class="a-input-group_manage">
          <a-input v-model:value="auditManagers" placeholder="请选择" class="selectInput" />
          <a-button type="primary">选择</a-button>
        </a-input-group>
      </a-form-item>
      <!-- <a-form-item label="" v-if="formState.enable">
        <div class="useScope">应用模块</div>
      </a-form-item> -->
    </a-form>
    <!-- <template v-for="(item, index) in formState.moduleSetups" v-if="formState.enable">
      <div class="selection" :class="'selection' + index">
        <a-form-item :label="item.moduleName">
          <a-checkbox-group
            v-model:value="item.selectedOptions"
            :options="item.opSetups.map((data: any) => ({
            'label': data.opName, 'value': data.opId
          }))"
          />
        </a-form-item>
      </div>
    </template> -->
    <!-- 新建模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="sensitive_modal">
      <template v-slot:body>
        <div class="searchIptBox">
          <div class="searchIpt">
            <a-tree-select class="AtreeSelect" v-model:value="selectOrgData" ref="siteDetail_treeSelect" show-search
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" allow-clear
              treeNodeFilterProp="name" :fieldNames="{
                children: 'children',
                label: 'name',
                value: 'id',
              }" tree-default-expand-all :tree-data="OrgData" @select="selectOrgTreeData">
            </a-tree-select>
            <a-input-search v-model:value="userName" placeholder="用户名/真实姓名" enter-button @search="getUsers({})" />
          </div>
          <div class="yxyh">已选用户</div>
        </div>

        <a-transfer v-model:target-keys="targetKeys" :data-source="userData.records" :disabled="disabled"
          :show-search="showSearch" :show-select-all="false" @change="onChange" class="threeMembertransfer">
          <template #children="{
            direction,
            filteredItems,
            selectedKeys,
            disabled: listDisabled,
            onItemSelectAll,
            onItemSelect,
          }">
            <a-table :row-selection="getRowSelection({
              disabled: listDisabled,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
              " :columns="direction === 'left' ? leftColumns : rightColumns" :data-source="filteredItems" size="small"
              :style="{ pointerEvents: listDisabled ? 'none' : null }" :custom-row="({ key } = { key: any }) => ({
                onClick: () => {
                  if (listDisabled) return;
                  onItemSelect(key, !selectedKeys.includes(key));
                },
              })
                " />
          </template>
        </a-transfer>
      </template>
    </base-modal>
    <div class="table-bottom_fiexd" :style="styleWidth">
      <a-button type="primary" :disabled="!btnPerm.includes('saveAble')" @click="saveButton">保存</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, reactive, nextTick, computed } from "vue";
import request from "@/api/index";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import baseModal from "@/components/modal/baseModal.vue";
import { any } from "vue-types";
import { message, SelectProps } from "ant-design-vue";
import {routerPerm} from '@/utils/common';
interface MockData {
  key: string;
  title: string;
  description: string;
  disabled: boolean;
}
type tableColumn = Record<string, string>;

const TableColumns = [
  {
    dataIndex: "userName",
    title: "用户名",
  },
  {
    dataIndex: "realName",
    title: "真实姓名",
  },
  {
    dataIndex: "orgName",
    title: "组织名称",
  },
];
interface MockData {
  key: string;
  title: string;
  description: string;
  disabled: boolean;
}
// interFace
interface dataSourceType {
  [propName: string]: any;
}
//data
const btnPerm = ref<any[]>([]);
const formState = ref<dataSourceType>({
  //   enable: false,
  status_setting: {
    params: "enable",
    label: "是否开启分级保护",
    rule: {
      required: false,
      trigger: ["blur"],
      msg1: "站点域名不可为空！",
      msg2: "列表或回收站中已存在相同的域名，请重新输入！",
      api: "fetchsiteManageTabledDataUniqueCheck",
    },
  },
  ClassificationMark: {
    label: "系统密级标记",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "请填写系统密级标记内容！",
    },
    value: '',
  },
  secret_setting: {
    params: "userSecretId",
    label: " 系统密级设置",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "系统密级设置不可为空！",
    },
  },
  ctl_setting: {
    params: "enableContentCtl",
    label: " 是否开启内容密级",
    rule: {
      required: false,
      trigger: ["blur"],
      message: "系统密级设置不可为空！",
    },
  },
  Annex_setting: {
    params: "enableContentAnnexCtl",
    label: " 是否开启附件密级",
    rule: {
      required: false,
      trigger: ["blur"],
      message: "系统密级设置不可为空！",
    },
  },
  safeManager_setting: {
    params: "securityManagers",
    label: "安全管理员",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "安全管理员不可为空！",
    },
  },
  auditManager_setting: {
    params: "auditManagers",
    label: "审计管理员",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "审计管理员不可为空！",
    },
  },
  section: "分保角色配置",
});
const isDeleteSid = ref(false); //之前选择的密级是否被删除
let securityManagers = ref("");
let auditManagers = ref("");
const modAlProps: dataSourceType = reactive({
  width: "1080",
  title: "选择用户",
});
const threeMemberForm = ref();
const isVisible = ref<Boolean>(false);
const buttons = ref<dataSourceType[]>([
  {
    text: "保存",
    "html-type": "submit",
    keepAlive: true,
  },
]); //模态框button按钮个数和文案修改

const targetKeys = ref<any[]>([]);
const disabled = ref<boolean>(false);
const showSearch = ref<boolean>(false);
const leftColumns = ref<tableColumn[]>(TableColumns);
const rightColumns = ref<tableColumn[]>(TableColumns);
const tempTargetKeys = ref<string[]>([]);
const userSecretIdOptions = ref<SelectProps["options"]>([]);
const onChange = (nextTargetKeys: string[]) => {
  tempTargetKeys.value = nextTargetKeys;
};
// 内容密级
const enableContentCtl = (data: any) => {
  if (!data.target.value) {
    formState.value.enableContentAnnexCtl = false;
  }
};

// 密级数据
const getAllUserSecretList = async () => {
  const data = (await request.fetchAllUserSecretList({})) || [];
  let arrSERid: any = [];
  data.length &&
    data.forEach((item: dataSourceType) => {
      userSecretIdOptions.value?.push({ label: item.name, value: item.id });
      item.value = item.name;
      arrSERid.push(item.id)
    });
  nextTick(() => {
    if (formState.value.userSecretId) {
      if (!arrSERid.includes(formState.value.userSecretId)) {
        isDeleteSid.value = true;
        formState.value.userSecretId = '';
      }
    }
  })

  // sequrityOptions.value = [{ name: "全部", id: 0, value: "全部" }, ...data];
};
const getRowSelection = ({
  disabled,
  selectedKeys,
  onItemSelectAll,
  onItemSelect,
}: Record<string, any>) => {
  return {
    getCheckboxProps: (item: Record<string, string | boolean>) => ({
      disabled: disabled || item.disabled,
    }),
    onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
      const treeSelectedKeys = selectedRows
        .filter((item) => !item.disabled)
        .map(({ key }) => key);
      onItemSelectAll(treeSelectedKeys, selected);
    },
    onSelect({ key }: Record<string, string>, selected: boolean) {
      onItemSelect(key, selected);
    },
    selectedRowKeys: selectedKeys,
  };
};
//穿梭框相关数据
const selectOrgData = ref("");
const OrgData = ref<dataSourceType[]>([]);
const userName = ref("");
const isSafa_audit = ref("");
let userData = reactive<dataSourceType>({
  records: [],
  total: "",
  size: "",
});
let saveData = ref({});
//computed
securityManagers = computed(() =>
  formState.value.securityManagers?.map((item: dataSourceType) => item.name).join(",")
);
auditManagers = computed(() =>
  formState.value.auditManagers?.map((item: dataSourceType) => item.name).join(",")
);
saveData = computed(() => {
  let dataTemp = JSON.parse(JSON.stringify(formState.value));
  dataTemp.auditManagers = dataTemp.auditManagers.map((item: dataSourceType) => item.id);
  dataTemp.securityManagers = dataTemp.securityManagers.map(
    (item: dataSourceType) => item.id
  );
  return dataTemp;
});

// onMounted
onMounted(() => {
  btnPerm.value = routerPerm()
  useFixeWidth();
  // getThreeMemberSetting();
  fetchReinsurance();

});
//methods
const selectMember = (param: any) => {
  targetKeys.value = formState.value[param]?.map((item: dataSourceType) => item.id);
  fetchUserOrgTree();
  getUsers({});
  nextTick(() => {
    isVisible.value = true;
  });
  isSafa_audit.value = param;
};
const fetchReinsurance = async () => {
  // 调接口获取配置
  await request.fetchReinsurance({}).then((res: any) => {
    if (res) {
      formState.value.ClassificationMark.value = res.secretSysTitle;
      let data = res;
      formState
      let dataTemp = Object.assign(data, formState.value);
      formState.value = dataTemp;
      console.log()
      nextTick(() => {
        getAllUserSecretList();
      })
    }
  });
};
const buttonMessage = async (msg: dataSourceType) => {
  targetKeys.value = tempTargetKeys.value;
  formState.value[isSafa_audit.value] = [];
  let userNames: any = [];
  userData.records.forEach((item: dataSourceType) => {
    targetKeys.value.forEach((data: dataSourceType) => {
      if (data == item.id) {
        formState.value[isSafa_audit.value].push({
          id: item.id,
          name: item.userName,
        });
      }
    });
  });
  isVisible.value = false;
};
//获取当前用户可见组织树
const fetchUserOrgTree = async () => {
  const data = (await request.fetchUserOrgTree()) || [];

  OrgData.value = [
    { name: "全部", id: "" },
    ...data.filter((item: dataSourceType) => !item.authAble),
  ];
};
const getUsers = async (datas: dataSourceType) => {
  // 获取表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 100000000,
    name: userName.value,
    orgId: selectOrgData.value,
  };
  const telData = (await request.fetchUserPage(data)) || {};
  let reqData = telData;
  userData.total = reqData.total;
  userData.size = reqData.size;
  userData.records = reqData.records;
  userData.records?.map((item: dataSourceType) => (item.key = item.id));
};
const selectOrgTreeData = () => {
  getUsers({});
};
const saveButton = () => {
  threeMemberForm.value
    .validate()
    .then(() => {
      const params = JSON.parse(JSON.stringify(saveData.value))
      params.secretSysTitle = formState.value.ClassificationMark.value
      request.fetchRreinsuranceUpdate(params).then((res: dataSourceType) => {
        if ((res.code = "00000 00000")) {
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      });
    })
    .catch(() => { });
};
</script>

<style lang="less">
.setting {
  padding: 16px;
  background: #fff;
  height: calc(100% - 120px);
  overflow: auto;

  .tips {
    margin-bottom: 24px;
  }

  .isOpen {
    margin-left: 8px;
  }

  .userSecret {
    width: 200px;
  }

  .titleSetting {
    height: 40px;
    font-size: 14px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
    line-height: 40px;
    background: #f7f8fa;
    border-radius: 2px 2px 2px 2px;
    position: relative;
    padding-left: 24px;
    margin-top: 24px;
  }

  .titleSetting:after {
    width: 3px;
    height: 12px;
    background: var(--theme_button_active_bg_color, #1050c7);
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
    content: "";
    position: absolute;
    left: 3px;
    z-index: 1;
    top: 14px;
  }

  .selectInput {
    width: 300px;

    .ant-input {
      height: 32px;
      font-size: 14px;
      color: #333;
    }

    .ant-btn {
      height: 32px;
      font-size: 14px;
      color: #333;
    }
  }

  .useScope {
    margin-left: 24px;
  }

  .selection {
    .ant-form-item-label {
      width: 90px;
    }
  }

  .table-bottom_fiexd {
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    background: #fff;
    box-shadow: 0px -12px 48px 16px rgba(0, 0, 0, 0.03),
      0px -9px 28px 0px rgba(0, 0, 0, 0.05), 0px -6px 16px -8px rgba(0, 0, 0, 0.08);
  }
}

.searchIptBox {
  display: flex;
  align-items: center;

  .yxyh {
    margin-left: 40px;
    margin-bottom: 24px;
  }
}

.searchIpt {
  width: calc(50% - 20px);
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;

  .ant-input-group-wrapper {
    width: 40%;
  }

  .ant-select {
    width: 50%;
  }
}

.threeMembertransfer {
  .ant-transfer-list-header {
    display: none;
  }
}

.a-input-group_manage {
  position: relative;
  width: 365px;
  cursor: pointer;
}

.a-input-group_manage::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
</style>
